import React, { Component } from 'react'
// import { SettingAlert } from '../../components'
import { TreeComponent, ModalForm } from '../../components'
import Dimensions from 'react-dimensions'
import { fetchData  } from "../../components/AjaxConsumer.js";
import { Button, Form, Row, Col, Modal, Spin, Alert, Upload, message, Icon } from 'antd';
const WrappedAdvancedSearchForm = Form.create()(ModalForm);
const SecondNodeForm = Form.create()(ModalForm);
const SecondNodeFormOther = Form.create()(ModalForm);
const SonNodeStructureForm = Form.create()(ModalForm);
const confirm = Modal.confirm;
function warning() {
    Modal.warning({
        title: '请先选择一个节点',
    });
}

class ListStructurePage extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            selectedKeys: [],
            selectedName: '',
            treeSelectBackData: '',
            optionData: [],
            node:'',
            structureLevel:'',
            optionDataSClass: [],
            optionDataPL:[],
            optionDataSType:[],
            optionDataParentSName:[],
            structureClass:''
        };
    }
    componentDidMount() {
      //console.log("---------------------",this.props.StandarObj);

    }
    loading = (flag) => {
        this.setState({
            loading: flag
        })
    }
    //树组件点击，更新form
    upDataForm = (resData,selectedKeys,selectedName,info) => {
        //模拟延时，会有loading动画过度
        //console.log("选中：",selectedName,resData);
        const nodeStr = info.node.props.pos;
        const node = nodeStr.split("-").join("").length;
        setTimeout(function(){
            this.setState({
                loading: false,
                treeSelectBackData: resData,
                selectedKeys: selectedKeys,
                node:node,
                selectedName: selectedName,
                structureClass:resData.data.structureClass,
                structureLevel:resData.data.structureLevel
            })
        }.bind(this),500);

        this.getOptionData('parentStructureName');//组织结构顶级节点
        this.getOptionData('standard_class');//组织大类
        this.getOptionData('structure_product_line');//产品线
        this.getOptionData('structure_structure_type');//组织类别
    }

    //获取设备大类
    getOptionData = (type) =>{
        //console.log("----------下拉框-----------");
        let options;
       if(type == "parentStructureName"){
         options= {
             url: '/base/structure/fup',
             type: 'post',
             condition: {
                   parentId: '0'
                   //   deleteId: checkedKeys
               }   //请求条件
         };
       }else{
         options= {
             url: `/base/dic/get/${type}`,
             type: 'get'
         };
       }

       fetchData(this,options,(resData)=>{
           //console.log('---resData-------------', resData.data);
           if(type == "standard_class"){
             this.setState({
                   optionDataSClass: resData.data
               });
           }else if(type == "structure_product_line"){
             this.setState({
                   optionDataPL: resData.data
               });
           }else if(type == "structure_structure_type"){
             this.setState({
                   optionDataSType: resData.data
               });
           }else if(type == "parentStructureName"){
             this.setState({
                   optionDataParentSName: resData.data
               });
           }

       });
    }




    //增加顶级节点
    addTopNode = () => {
      this.getOptionData('parentStructureName');//组织结构顶级节点
      this.getOptionData('standard_class');//组织大类
      this.getOptionData('structure_product_line');//产品线
      this.getOptionData('structure_structure_type');//组织类别
      this.getOptionData('parentStructureName');
        this.setState({
            treeSelectBackData: {addTopNode:true,parentStructureId:'',parentStructureName:'none'} //以后判断输出空表单使用
        })
    }

    //增加二级节点
    addSecondNode = () => {
      this.getOptionData('parentStructureName');//组织结构顶级节点
      this.getOptionData('standard_class');//组织大类
      this.getOptionData('structure_product_line');//产品线
      this.getOptionData('structure_structure_type');//组织类别
      this.getOptionData('parentStructureName');
        this.setState({
            treeSelectBackData: {addSecond:true,parentStructureId:'',parentStructureName:'',structureLevel:'0'} //以后判断输出空表单使用
        })
    }

    //增加子节点
    addSonNode = () => {
      this.getOptionData('parentStructureName');//组织结构顶级节点
      this.getOptionData('standard_class');//组织大类
      this.getOptionData('structure_product_line');//产品线
      this.getOptionData('structure_structure_type');//组织类别
        let selectedKeys = this.state.selectedKeys;
        let selectedName = this.state.selectedName;
        let structureLevel = this.state.structureLevel;
        let structureClass = this.state.structureClass;
        //console.log(selectedKeys,selectedName);
        if (typeof(selectedKeys) != 'undefined' && selectedKeys.length) {

            this.setState({
                treeSelectBackData: {
                  sonNode:true,
                  parentStructureId:selectedKeys[0],
                  parentStructureName:selectedName,
                  structureLevel:structureLevel,
                  structureClass:structureClass
                }
            })
        } else {
            warning();
        }
    }

    //删除节点
    deleteNode = () => {
      let selectedKeys = this.state.selectedKeys;
       let selectedName = this.state.selectedName;
       if (typeof(selectedKeys) != 'undefined' && selectedKeys.length) {
           let options = {
               url: '/base/structure/d/',          //请求地址
               type: 'post',    //请求方式
               contentType: 'application/x-www-form-urlencoded',
               condition: {
                   structureId: selectedKeys[0]
                   //   deleteId: checkedKeys
               }   //请求条件
           };
           let that = this;
           confirm({
               title: '提示',
               content: '确定要删除吗?',
               onOk() {
                   fetchData(that, options, that.callbackUpdata);
               },
               onCancel() {
                   console.log('Cancel');
               },
           });

        } else {
            warning();
        }
    }



    //出现初始页面（请选择左侧节点）
    callbackUpdata = (resData) => {
        this.setState({
            treeSelectBackData: null,
            selectedKeys: [],
            selectedName: null
        })
        //从新加载tree组件
        if (this.refs.TreeComponent.refleshData){
            this.refs.TreeComponent.refleshData();
        }
    }

    render() {
        //高度自适应
        let {containerHeight, subtractHeight, ...props} = this.props;
        const { node, optionDataParentSName, optionDataSClass,optionDataPL,optionDataSType } = this.state;
        //console.log("node-------",node);
        //subtractHeight 和 subtractWidth 是页面传过来的值
        if(typeof subtractHeight !== 'undefined'){
            containerHeight = containerHeight - subtractHeight;
        }

        let optionData = this.state.optionData.data ? this.state.optionData.data : [];
        let newFormObj = this.state.treeSelectBackData ? this.state.treeSelectBackData : {code:'0'};


        let formAlerSize = 'large'; //弹出框的大小 只有'large'和'small'两种值 （必须,输错时默认为large）

    	//console.log("对象是------：",newFormObj);


        //组织结构顶级节点 空表单
        let getStructureTopNodeForm = [
          {
              type : 'input',
              showName : '组织名称',
              name : 'structureName',
              required: true
          }
        ];

        //组织结构二级节点 空表单
        let getStructureSecondNodeForm=[
              {
                  type : 'select',
                  showName : '父级组织名称',
                  name : 'parentStructureId',
                  optionList:[
                      {
                          optionKey:'',
                          optionShow:''
                      }
                  ],
                  initialValue : newFormObj?newFormObj.parentStructureName:'顶级节点',
                  required: true
              },{
                      type : 'input',
                      showName : '组织名称',
                      name : 'structureName',
                      initialValue : '',
                      required: true
              },{
                 type : 'select',
                 showName : '所属产线',
                 name : 'productLine',
                 optionList:[
                     {
                         optionKey:'',
                         optionShow:''
                     }
                 ],
                 required: true
             },{
                type : 'select',
                showName : '组织大类',
                name : 'structureClass',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    }
                ],
                required: true
            },{
                type : 'input',
                showName : '序号',
                name : 'structureNumber',
            },{
                type : 'input',
                showName : '公司名',
                name : 'companyName',
            },{
                type : 'input',
                showName : '单位地址',
                name : 'companyAdress',
            },{
                type : 'input',
                showName : '联系电话',
                name : 'telephone',
            },{
                type : 'input',
                showName : '传真',
                name : 'fax',
            },{
                type : 'input',
                showName : '邮政编码',
                name : 'postcode',
            },{
                type : 'textarea',
                showName : '备注',
                name : 'remark',
            }
        ];
        //组织结构二级节点 查看修改表单
        let getStructureSecondNodeFormData=[
          {
              type : 'select',
              showName : '父级组织名称',
              name : 'parentStructureId',
              optionList:[
                  {
                      optionKey:'',
                      optionShow:''
                  }
              ],
              initialValue : newFormObj.data ? newFormObj.data.parentStructureId:'',
              required: true
          },{
                type : 'input',
                showName : '组织名称',
                name : 'structureName',
                initialValue : newFormObj.data ? newFormObj.data.structureName:'',
                required: true
            },{
               type : 'select',
               showName : '所属产线',
               name : 'productLine',
               optionList:[
                   {
                       optionKey:'',
                       optionShow:''
                   }
               ],
               initialValue : newFormObj.data ? newFormObj.data.productLine:'',
               required: true
           },{
              type : 'select',
              showName : '组织大类',
              name : 'structureClass',
              optionList:[
                  {
                      optionKey:'',
                      optionShow:''
                  }
              ],
              initialValue : newFormObj.data ? newFormObj.data.structureClass:'',
              required: true
          },{
                type : 'number',
                showName : '序号',
                name : 'structureNumber',
                initialValue : newFormObj.data ? newFormObj.data.structureNumber:'',
            },{
                type : 'hiddenInput',
                name : 'structureLevel',
                initialValue : newFormObj.data?newFormObj.data.structureLevel:''
            },{
                type : 'hiddenInput',
                name : 'structureId',
                initialValue : newFormObj.data ? newFormObj.data.structureId : ''
            },{
                type : 'input',
                showName : '公司名',
                name : 'companyName',
                initialValue : newFormObj.data ? newFormObj.data.companyName:'',
            },{
                type : 'input',
                showName : '单位地址',
                name : 'companyAdress',
                initialValue : newFormObj.data ? newFormObj.data.companyAdress:'',
            },{
                type : 'input',
                showName : '联系电话',
                name : 'telephone',
                initialValue : newFormObj.data ? newFormObj.data.telephone:'',
            },{
                type : 'input',
                showName : '传真',
                name : 'fax',
                initialValue : newFormObj.data ? newFormObj.data.fax:'',
            },{
                type : 'input',
                showName : '邮政编码',
                name : 'postcode',
                initialValue : newFormObj.data ? newFormObj.data.postcode:'',
            },{
                type : 'textarea',
                showName : '备注',
                name : 'remark',
                initialValue : newFormObj.data ? newFormObj.data.remark:'',
            }
        ];

        //组织结构子节点 空表单
        let getStructureSonNodeForm=[
            {
                type : 'select',
                showName : '父级组织名称',
                name : 'parentStructureId',
                optionList:[
                    {
                        optionKey:newFormObj.parentStructureId,
                        optionShow:newFormObj.parentStructureName
                    }
                ],
                initialValue : newFormObj ? newFormObj.parentStructureId:'',
                required: true,
                disable: true
            },{
                type : 'select',
                showName : '组织大类',
                name : 'structureClass',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    }
                ],
                initialValue : newFormObj ? newFormObj.structureClass:'',
                disable: true
                //required: true
            },{
                  type : 'input',
                  showName : '组织名称',
                  name : 'structureName',
                  required: true,

              },{
                type : 'select',
                showName : '组织类别',
                name : 'structureType',
                optionList:[
                    {
                        optionKey:'',
                        optionShow:''
                    }
                ],

                //required: true
            },{
                  type : 'number',
                  showName : '序号',
                  name : 'structureNumber',

              },{
                type : 'input',
                showName : '实验室编码',
                name : 'structureCode',
                pattern:new RegExp(/^[a-zA-Z0-9]{5,5}$/),
                errorMessage:'请输入五位数字 或 字母'
            },{
                type : 'select',
                showName : '共用台位',
                name : 'moreTableStatus',
                initialValue : 'N',
                optionList:[
                    {
                        optionKey:'Y',
                        optionShow:'是'
                    },
                    {
                        optionKey:'N',
                        optionShow:'否'
                    }
                ],
                required: true
            },{
                  type : 'textarea',
                  showName : '备注',
                  name : 'remark',

              }
        ];
        //组织结构子节点 查看修改表单
        let getStructureSonNodeFormData=[
          {
              type : 'input',
              showName : '父级组织名称',
              name : 'parentStructureName',
              initialValue : newFormObj.data ? newFormObj.data.parentStructureName:'',
              disable: true
          },{
              type : 'select',
              showName : '组织大类',
              name : 'structureClass',
              optionList:[
                  {
                      optionKey:'',
                      optionShow:''
                  }
              ],
              initialValue : newFormObj.data ? newFormObj.data.structureClass:'',
              //required: true
              disable: true
          },{
                type : 'input',
                showName : '组织名称',
                name : 'structureName',
                initialValue : newFormObj.data ? newFormObj.data.structureName:'',
                required: true
            },{
              type : 'select',
              showName : '组织类别',
              name : 'structureType',
              optionList:[
                  {
                      optionKey:'',
                      optionShow:''
                  }
              ],
              initialValue : newFormObj.data ? newFormObj.data.structureType:'',
              //required: true
          },{
                type : 'number',
                showName : '序号',
                name : 'structureNumber',
                initialValue : newFormObj.data ? newFormObj.data.structureNumber:'',
            },{
                type : 'input',
                showName : '实验室编码',
                name : 'structureCode',
                initialValue : newFormObj.data ? newFormObj.data.structureCode:'',
                pattern:new RegExp(/^[a-zA-Z0-9]{5,5}$/),
                errorMessage:'请输入五位数字 或 字母'
            },{
                type : 'select',
                showName : '公用台位',
                name : 'moreTableStatus',
                initialValue : newFormObj.data ? newFormObj.data.moreTableStatus:'N',
                optionList:[
                    {
                        optionKey:'Y',
                        optionShow:'是'
                    },
                    {
                        optionKey:'N',
                        optionShow:'否'
                    }
                ],
                required: true
            },{
                type : 'textarea',
                showName : '备注',
                name : 'remark',
                initialValue : newFormObj.data ? newFormObj.data.remark:'',
            },{
                type : 'hiddenInput',
                name : 'structureId',
                initialValue : newFormObj.data ? newFormObj.data.structureId : ''
            }
        ];
        //optionDataSClass,optionDataPL,optionDataSType
        if(optionDataSType.length > 0){
            let options = [];
            optionDataSType.map((item, index) => {
              let tempObj = {};
                tempObj.optionKey = item.dicCode;
                tempObj.optionShow = item.dicName;
                options.push(tempObj);
            })
            //console.log(`options---------`,options);
            getStructureSonNodeForm[3].optionList = options;
            getStructureSonNodeFormData[3].optionList = options;
        }
        if(optionDataPL.length > 0){
            let options = [];
            optionDataPL.map((item, index) => {
              let tempObj = {};
                tempObj.optionKey = item.dicCode;
                tempObj.optionShow = item.dicName;
                options.push(tempObj);
            })

            //getStructureTopNodeForm[1].optionList = options;
            getStructureSecondNodeForm[2].optionList = options;
            getStructureSecondNodeFormData[2].optionList = options;
        }
        if(optionDataSClass.length > 0){
            let options = [];
            optionDataSClass.map((item, index) => {
              let tempObj = {};
                tempObj.optionKey = item.dicCode;
                tempObj.optionShow = item.dicName;
                options.push(tempObj);
            })
            getStructureSecondNodeForm[3].optionList = options;
            getStructureSecondNodeFormData[3].optionList = options;
            //getStructureTopNodeForm[3].optionList = options;
            getStructureSonNodeForm[1].optionList = options;
            getStructureSonNodeFormData[1].optionList = options;
        }
        if (optionDataParentSName.length > 0){

            let options = [];
            optionDataParentSName.map((item, index) => {
                let tempObj = {};
                tempObj.optionKey = item.structureId;
                tempObj.optionShow = item.structureName;
                options.push(tempObj);
            })
            getStructureSecondNodeForm[0].optionList = options;
            getStructureSecondNodeFormData[0].optionList = options;
        }



      let ele;
      let loading = this.state.loading;
      if(loading) {
          ele =
              <div style={{
                  textAlign: 'center',
                  borderRadius: '4px',
                  height: '100%',
                  paddingTop:'20%'
              }}>
                  <Spin size="large" /> 加载中...
              </div>
        } else if (newFormObj.code == '1') {
            //正常渲染的表单
            if(node == '3'){
              ele =<div>
	                <h2 style={{
	                    textAlign: 'center',
	                    color: '#666',
	                    fontSize: '20px',
	                    marginBottom: '20px'
	                }}>
	                    修改{this.state.selectedName}
	                </h2>
	                <SecondNodeForm
	                    callbackUpdata={this.callbackUpdata}
	                    formAlerSize={formAlerSize}
	                    formUrl="/base/structure/u/"
	                    getFormData={getStructureSecondNodeFormData}
	                />
	            </div>
            }else if(node >= '4'){
              ele =<div>
	                <h2 style={{
	                    textAlign: 'center',
	                    color: '#666',
	                    fontSize: '20px',
	                    marginBottom: '20px'
	                }}>
	                    修改 {this.state.selectedName}
	                </h2>
	                <WrappedAdvancedSearchForm
	                    callbackUpdata={this.callbackUpdata}
	                    formAlerSize={formAlerSize}
	                    formUrl="/base/structure/u/"
	                    getFormData={getStructureSonNodeFormData}
	                />
	            </div>
            }


        } else if (newFormObj.addTopNode) {
            //点击新增顶级节点的空表单
            ele =<div>
                    <h2 style={{
                        textAlign: 'center',
                        color: '#666',
                        fontSize: '20px',
                        marginBottom: '20px'
                    }}>
                        添加主节点
                    </h2>
                    <WrappedAdvancedSearchForm
                        callbackUpdata={this.callbackUpdata}
                        formAlerSize={formAlerSize}
                        formUrl="/base/structure/c/"
                        getFormData={getStructureTopNodeForm}
                    />
                </div>
        }else if (newFormObj.addSecond) {
            //点击新增顶级节点的空表单
            ele =<div>
                    <h2 style={{
                        textAlign: 'center',
                        color: '#666',
                        fontSize: '20px',
                        marginBottom: '20px'
                    }}>
                        添加二级节点
                    </h2>
                    <SecondNodeFormOther
                        callbackUpdata={this.callbackUpdata}
                        formAlerSize={formAlerSize}
                        formUrl="/base/structure/c/"
                        getFormData={getStructureSecondNodeForm}
                    />
                </div>
        } else if (newFormObj.sonNode) {
            //点击新增顶级节点的空表单
            ele =<div>
                    <h2 style={{
                        textAlign: 'center',
                        color: '#666',
                        fontSize: '20px',
                        marginBottom: '20px'
                    }}>
                        添加 { newFormObj.parentStructureName} 子节点
                    </h2>
                    <SonNodeStructureForm
                        callbackUpdata={this.callbackUpdata}
                        formAlerSize={formAlerSize}
                        formUrl="/base/structure/c/"
                        getFormData={getStructureSonNodeForm}
                    />
                </div>
        } else {
            //未点击页面
            ele =
                <Alert
                    style={{marginRight:'50px'}}
                    message="温馨提示"
                    description="操作前，请先点击选择左侧需要选择的节点"
                    type="info"
                    showIcon
                />
        }


        return (
            <div className='formBoxStyle' style={{overflow:'hidden',height:'96%',backgroundColr:'#fff'}}>
                <div className='formTitle' style={{lineHeight: '40px',marginRight: '40px'}}>
                  <Row>
                    <Col span={6}>
                    <span className='left'>实验室组织管理</span>
                    </Col>

                         <Col span={18}>
                           <Button  type='primary' onClick={this.addTopNode} style={{margin:'2px 0px 0px 10px'}}>新增主节点</Button>
                           <Button  type='primary' onClick={this.addSecondNode} style={{margin:'2px 0px 0px 10px'}}>新增二级节点</Button>
                           <Button  type='primary' onClick={this.addSonNode} style={{margin:'2px 0px 0px 10px'}} >新增三级节点</Button>
                           <Button  type='primary' onClick={this.deleteNode} style={{margin:'2px 0px 0px 10px'}}>刪除</Button>

                         </Col>


                 </Row>
                </div>
                <Row  style={{height:containerHeight}}>
                    <Col  span={6} style={{backgroundColor:'#fff'}}>
                        <TreeComponent
                            ref = 'TreeComponent'
                            loading = {this.loading}
                            upDataForm = {this.upDataForm}
                            url='/base/structure/tree'
                            treeId = 'structureId'
                            treeName = 'structureName'
                            treeChildren = 'children'
                            titleClick = {true}
                            titleClickUrl = '/base/structure/r/'
                        />
                    </Col>
                    <Col span={18} style={{borderLeft:'1px solid #1d8ece',height:'100%',overflowY:'auto',overflowX:'hidden',padding:'30px 0px 30px 50px',backgroundColor:'#fff'}}>
                        {ele}
                    </Col>
                </Row>


            </div>
        );
    }
}
export default Dimensions({
    getHeight: function(element) {
        return window.innerHeight - 165;
    },
    getWidth: function(element) {
        let widthOffset = 270;
        return window.innerWidth - widthOffset;
    },
    containerStyle: {marginLeft: 5, marginRight: 5 } //, transitionProperty: 'width', transitionDuration: '0.5s', transitionTimingFunction:'linear'
})(ListStructurePage);
